package com.yantong.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.yantong.annotation.Auth;
import com.yantong.constant.*;
import com.yantong.controller.BaseController;
import com.yantong.enums.PayChannelEnum;
import com.yantong.exception.BDException;
import com.yantong.mapper.OrderMapper;
import com.yantong.mapper.OrderProductMapper;
import com.yantong.mapper.XLoginInfoMapper;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.*;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.service.xcx.XCXLoginService;
import com.yantong.utils.CusAccessObjectUtil;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: juzi
 * @date: 2021/10/25
 * @time: 16:12
 */
@ApiIgnore
@Controller
@RequestMapping("/wxapi/order")
public class ApiOrderController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOrderController.class);


    @Autowired
    private OrderService orderService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberIntegralService integralService;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private ProductCentreService productCentreService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProjectExpService projectExpService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductAuthorityService productAuthorityService;
    @Autowired
    private PayService payService;
    @Autowired
    private YFZPayutil yfzPayutil;
    @Autowired
    PayChannelService payChannelService;
    @Autowired
    private CentreService centreService;
    @Autowired
    private MyWxpayService myWxpayService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private XLoginInfoMapper xLoginInfoMapper;
    @Value("${weixin.pay.notify}")
    private String notifyUrl;

    @Value("${yfz.notify}")
    private String yfzNotifyUrl;

    @Value("${Applet.TemplatemsgCreateUserUrl}")
    private String templatemsgCreateUserUrl;

    /**
     * 获取订单详情
     */
    @RequestMapping("")
    @ResponseBody
    //@Auth
    public ResultVo getOrderById(String orderId, Long shopId, Long id, Integer iskuaidi) {
        logger.info("获取订单详情orderId：{}", orderId);
        logger.info("获取订单详情shopId：{}", shopId);
        Order order = null;
        //快递直发商品订单
        if (iskuaidi != null && iskuaidi.intValue() == 1) {
            order = orderService.getByKeyAndProductId(Long.parseLong(orderId), id);
        } else {
            //普通团购订单
            if (orderId.contains("X_OC_")) {
                order = orderService.getByPayNo(orderId);
                if (order.getTrId() != null) {
                    order.setTicketRecord(ticketService.getRecordByKey(order.getTrId()));
                }
                List<OrderProduct> list = orderProductMapper.getByPayNo(orderId);
                if (CollectionUtils.isNotEmpty(list)) {
                    TradeConfig tc = null;
                    for (OrderProduct op : list) {
                        if (op.getTihuoday() == null) {
                            if (tc == null) {
                                tc = configService.getTradeConfig(order.getCentreId());
                            }
                            if (tc != null) {
                                op.setTihuoday(tc.getExpectedPickTime());
                            }
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(list) && iskuaidi != null && iskuaidi.intValue() == 1) {
                    order.setSaddress(list.get(0).getSaddress());
                }
                order.setOrderProducts(list);
                order.setStatusName(OrderStatus.get(order.getStatus()));
            } else {
                order = orderService.getByKey(Long.parseLong(orderId));

            }
        }
        if (CollectionUtils.isNotEmpty(order.getOrderProducts())) {
            order.setSaddress(order.getOrderProducts().get(0).getSaddress());
        }
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", order);
        //如果下单门店和当前不是一个门店
        if (null != shopId && null != order && !shopId.equals(order.gettMid())) {
            Member shop = memberService.getDetail(order.gettMid());
            resultVo.put("shop", shop);
        }
        Member member = memberService.getDetail(order.getMid());
        if (null != order && order.getStatus() == 0) { //待支付状态需要查询余额和积分信息

            double points = integralService.getMemberIntegralNew(order.getMid());

            resultVo.put("time", System.currentTimeMillis());
            resultVo.put("balance", member.getCredit2());
            resultVo.put("points", points);
        }
        resultVo.put("memLat", member.getLat());
        resultVo.put("memLng", member.getLng());

        return resultVo;
    }



    /**
     * 订单列表
     *
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/list")
    @ResponseBody
    @Auth
    public ResultVo getOrderList(ListOrderParams params, Integer offset, Integer limit) {

        PageUtils<Order> orders = orderService.listOrders(params, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", orders);
        return resultVo;
    }


    /**
     * 聚合支付
     *
     * @throws IOException
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/juhepay")
    @ResponseBody
    public Object getOrderJuhePayConfig(Long mid, String userId, String payAmount, Long centerId, String payType, Long teamId, String teamSeqId, Long trId) throws Exception {
        ResultVo resultVo = new ResultVo();

        if (ValidateUtil.isEmptyString(teamSeqId)) {
            return ResultVo.error();
        }
        Member teamMember = memberService.getTmByTeamSeqId(teamSeqId);
        if (null == teamMember) {
            throw new BDException("绑定的商户信息异常，请联系系统管理员");
        }

        centerId = teamMember.getCentreId();
        //centerId = 167L;
        teamId = teamMember.getId();


        BigDecimal payAmountNew = new BigDecimal(payAmount);

        if (trId != null) {
            //计算优惠金额
            BigDecimal discountPrice = orderService.calcTicketAmountJuhepay(trId, payAmountNew, centerId);
            payAmountNew = payAmountNew.subtract(discountPrice);
        }

        PayChannel payChannel = payChannelService.getFirstChannel(centerId);

        if (payAmountNew.compareTo(BigDecimal.ZERO) > 0) {
            logger.info("payChannel：==================");
//            if (StringUtils.isNotBlank(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.YPL.getCode())) {
                Member member = memberService.getByKey(mid);
                Centre centre = centreService.getCentreById(centerId);

                if (null == centre) {
                    logger.info("Centre is null===========");
                    return ResultVo.error("商户不存在");
                }
                Centre ytCentre = new Centre();
                if (centre.getCentreId() != 317L) {
                    ytCentre = centreService.getCentreById(317L);
                }
                //创建订单号
                JuheOrder order = orderService.createJuheOrder(mid, centerId, teamId, userId, payAmount, PayChannelEnum.YPL.getCode(), "WECHAT".equals(payType) ? PayType.WX_PAY : PayType.ZFB_PAY, payAmountNew, trId);
                List<OrderProduct> orderProductList = new ArrayList<>();
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.setProductId(666L);
                orderProduct.setProductName("无");
                orderProduct.setPrice(new BigDecimal(0));
                orderProduct.setTotal(1);
                orderProductList.add(orderProduct);

                String notifyUrl = templatemsgCreateUserUrl + "/notify/yfz/notify";
                if (order.getPayType() == PayType.WX_PAY) {
                    XLoginInfo xLoginInfo = new XLoginInfo();
                    xLoginInfo.setMobile(member.getLoginMobile());
                    xLoginInfo = xLoginInfoMapper.selectOne(xLoginInfo);
                    member.setAppOpenid(xLoginInfo.getOpenId());
                    resultVo = YFZPayutil.getjuhePayConfig(order, payAmountNew.doubleValue(), centre, ytCentre, orderProductList, member, "", 35, true, notifyUrl, teamMember);
                }
//            }
        } else {
            //金额为零的时候处理
            JuheOrder order = orderService.createJuheOrder(mid, centerId, teamId, userId, payAmount, PayChannelEnum.SXF.getCode(), "WECHAT".equals(payType) ? PayType.WX_PAY : PayType.ZFB_PAY, payAmountNew, trId);
            payService.juhePay(order.getId(), order.getOutTradeNo(), order.getOutTradeNo(), 0L);
            return resultVo.put("payFlag", true);
        }

        resultVo.put("payFlag", false);
        return resultVo;
    }

    /**
     * 售后订单条件查询订单列表
     *
     * @author xiangyi
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/worklist")
    @ResponseBody
    @Auth
    public ResultVo getWorkOrderlist(ListOrderParams params, Integer offset, Integer limit) {
        PageUtils<WorkListVo> orders = orderService.workOrderlistByParams(params, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", orders);
        return resultVo;
    }

    /**
     * 订单预处理提交
     */
    @RequestMapping("/precreate")
    @ResponseBody
    @Auth
    public ResultVo getOrderPreCreateInfo(@RequestBody OrderReq req) throws ParseException {
        if (req.getIsSpellgroup() != null && req.getIsSpellgroup() == 1) {
            //拼团订单不是发起人
            if (req.getOrderId() != null) {
                SpellGroupOrdVo vo = new SpellGroupOrdVo();
                vo.setMid(req.getMemberId());
                vo.setSgorderId(req.getOrderId());
                //查询是否参团
                List<Order> list = orderService.getSpellGroupOrdByMid(vo);
                if (CollectionUtils.isNotEmpty(list)) {
                    //已参团
                    return ResultVo.error("亲,你已参加过此团");
                }
            }
        }
        long start = System.currentTimeMillis();
        List<OrderProduct> orderProducts = new ArrayList<>();
        List<ProductCentre> productList = new ArrayList<>();
        if ((req.getIsCentreord() == null || req.getIsCentreord() == 0) && (req.getIsCentreUpgrade() == null || req.getIsCentreUpgrade() == 0)) {
            orderProducts = new ArrayList<>(req.getProducts().size());
            productList = new ArrayList<>(req.getProducts().size());
        }
        long now = System.currentTimeMillis();
        boolean overTime = false;
        boolean limit = false;
        Double packingFee = 0d;//包装费
        BigDecimal postage = BigDecimal.ZERO;//运费
        BigDecimal alldweight = BigDecimal.ZERO;//所有的重量
        BigDecimal allPrice = BigDecimal.ZERO;//所有的价格
        BigDecimal allIntegral = BigDecimal.ZERO;//所有的积分
        Integer orderType = ProductType.Normal.getType();

        List<Long> productGradeIds = new ArrayList<>();


        if ((req.getIsCentreord() == null || req.getIsCentreord() == 0) && (req.getIsCentreUpgrade() == null || req.getIsCentreUpgrade() == 0)
                && (req.getIsStores() == null || req.getIsStores() == 0)) {
            Member member = memberService.getByKey(req.getMemberId());
            for (MemberCartVo cart : req.getProducts()) {
                ProductCentre productDetail = productCentreService.getByKeyWithCache(cart.getProductId());

                //如果商品分类设置了商品类别。
                if (productDetail.getPcate() != null && productDetail.getPcate() != 0L) {
                    Category category = categoryService.getByKey(productDetail.getPcate());
                    if (category.getProductGradeId() != null && !productGradeIds.contains(category.getProductGradeId())) {
                        productGradeIds.add(category.getProductGradeId());
                    }
                }

                //重量叠加
                BigDecimal weightexit = productDetail.getWeight().multiply(new BigDecimal(cart.getTotal()));
                alldweight = alldweight.add(weightexit);

                //规格项
                Long skuId = null;
                if (StringUtils.isNotEmpty(cart.getSpecs())) {
                    ProductSkuCentre productSkuCentre = productCentreService.getSkuBySpecs(cart.getSpecs());
                    if (productSkuCentre != null) {
                        skuId = productSkuCentre.getId();
                        logger.info("============" + productDetail.getId() + productDetail.getTitle() + "======" + skuId);
                    } else {
                        return ResultVo.error(productDetail.getTitle() + "-规格选择有误，请重试！");
                    }
                    //cart.setMarketprice(productSkuCentre.getMarketprice().add(cart.getMarketprice()));
                    productDetail.setCheckSkuTitle(productSkuCentre.getTitle());
                    productDetail.setSkuId(skuId);
                    List<ProductSkuCentre> list = new ArrayList<>();
                    list.add(productSkuCentre);
                    productDetail.setSkus(list);
                }

                //价格叠加
                BigDecimal totalMarketPrice = cart.getMarketprice().multiply(new BigDecimal(cart.getTotal()));
                BigDecimal totalIntegral = BigDecimal.ZERO;
                if (cart.getConsumptionIntegral() != null) {
                    totalIntegral = cart.getConsumptionIntegral().multiply(new BigDecimal(cart.getTotal()));
                }
                allPrice = allPrice.add(totalMarketPrice);
                allIntegral = allIntegral.add(totalIntegral);
                Date endTime = productDetail.getTimeend();
                Date startTime = productDetail.getTimestart();
                if (!productDetail.getProductType().equals(orderType)) {
                    orderType = productDetail.getProductType();
                }
                if (productDetail.getIsTeamBuy() == 1 && productDetail.getStartLimit() != null && cart.getTotal() < productDetail.getStartLimit()) {
                    limit = true;
                    continue;
                }
                if (productDetail.getIsTeamBuy() == 1 && member.getIsteam() != 3) {
                    continue;
                }

                //判断是否已经停售
                if ((endTime != null) && (now > endTime.getTime())) {
                    overTime = true;
                    continue;
                }

                //判断是否开售
                if ((startTime != null) && (now < startTime.getTime())) {
                    overTime = true;
                    continue;
                }

                cart.setCentreId(productDetail.getCentreId());
                productList.add(productDetail);
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.setProductId(cart.getProductId());
                orderProduct.setSkuId(skuId == null ? cart.getSkuId() : skuId);
                orderProduct.setPrice(BigDecimal.valueOf(productDetail.getMarketprice().floatValue() * cart.getTotal()));
                orderProduct.setTotal(cart.getTotal());
                orderProduct.setIsKuaidi(productDetail.getIsKuaidi());
                orderProducts.add(orderProduct);
            }
            double points = integralService.getMemberIntegralNew(member.getId());
            if (BigDecimal.valueOf(points).compareTo(allIntegral) < 0) {
                if (req.getCenterId() == 311L) {
                    throw new BDException("积分不足！");
                } else {
                    throw new BDException("金币不足！");
                }

            }
        }

        Member member = memberService.getByKey(req.getMemberId());

        req.setOrderType(orderType);
        ResultVo resultVo = new ResultVo();
        List<TicketRecord> coupons;
        if (req.getIsCentreord() != null && req.getIsCentreord() == 1) {//购买版本
            ProjectExpVo params = new ProjectExpVo();
            params.setType(0);
            params.setId(req.getProjectExpId());
            ProjectExp projectExp = projectExpService.listProjectExp(params);
            resultVo.put("data", projectExp);
            resultVo.put("isCentreord", req.getIsCentreord());
            BuyProjectVo buyProjectVo = orderService.calcProjectExpCharge(member, req.getServiceDays(), projectExp);
            resultVo.put("buyProjectInfo", buyProjectVo);
        } else if (req.getIsCentreUpgrade() != null && req.getIsCentreUpgrade() == 1) {
            //店主升级为超级店主
            if (member.getIsCentre() != null && member.getIsCentre() != 0) {
                resultVo.put("data", "升级超级店主预提交暂无业务处理");
                resultVo.put("isCentreUpgrade", req.getIsCentreUpgrade());
            } else {
                throw new BDException("请先成为店主");
            }
        } else if (req.getIsStores() != null && req.getIsStores() == 1) {
            //店主申请
            resultVo.put("data", "升级店主预提交暂无业务处理");
        } else {//购买商品
            coupons = ticketService.getTicketRecords(req, productGradeIds);
            if (null != coupons && coupons.size() > 0) {
                coupons = coupons.stream().sorted(Comparator.comparing(TicketRecord::getAmount).reversed()).collect(Collectors.toList());
            }
            BigDecimal discountPrice = BigDecimal.ZERO;
            if (req.getCouponId() != null) {
                BigDecimal goodsPrice = BigDecimal.ZERO;
                List<ProductCentre> productCentreList = new ArrayList<>();
                Map<String, String> skuMap = new HashMap<>(16);
                for (MemberCartVo memberCartVo : req.getProducts()) {
                    goodsPrice = goodsPrice.add(memberCartVo.getMarketprice());
                    ProductCentre productCentre = productCentreService.getByKey(memberCartVo.getProductId());
                    skuMap.put(productCentre.getId().toString(), memberCartVo.getSpecs());
                    productCentreList.add(productCentre);
                }
                //计算优惠券金额
                discountPrice = orderService.calcTicketAmount(req.getCouponId(), goodsPrice, req.getCenterId(), productCentreList,
                        req.getCateringType(), skuMap, postage);
            }


            TradeConfig tradeConfig1 = configService.getTradeConfig(req.getCenterId());
            Double packingFee1;
            packingFee1 = tradeConfig1.getPackingFee();


            resultVo.put("couponPrice", discountPrice);
            resultVo.put("coupons", coupons);
            resultVo.put("overtime", overTime);
            resultVo.put("limit", limit);
            //包装费
            if (req.getOrderType().equals(6)) {
                if (ValidateUtil.isNotEmptyObjectOrString(packingFee1)) {
                    resultVo.put("packingFee", packingFee1);
                } else {
                    resultVo.put("packingFee", 0);
                }
            } else {
                resultVo.put("packingFee", packingFee);
            }
            resultVo.put("postage", postage);
            //总重
            resultVo.put("allWeight", alldweight);
            //价格
            resultVo.put("goodsPrice", allPrice);
            //订单总价
            BigDecimal orderPrice = allPrice.add(postage).add(new BigDecimal(packingFee));
            resultVo.put("orderPrice", orderPrice);
            //实付金额
            BigDecimal payPrice = orderPrice;
            if (discountPrice.compareTo(BigDecimal.ZERO) > 0) {
                payPrice = payPrice.subtract(discountPrice);
            }
            resultVo.put("payPrice", payPrice);
        }
        resultVo.put("success", true);
        if ((req.getIsCentreord() == null || req.getIsCentreord() == 0) && (req.getIsCentreUpgrade() == null || req.getIsCentreUpgrade() == 0)
                && (req.getIsStores() == null || req.getIsStores() == 0)) {
            resultVo.put("data", productList);
        }

        logger.info("预订单耗费时间：{}", System.currentTimeMillis() - start);
        return resultVo;
    }


    /**
     * 提交订单
     *
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/create")
    @ResponseBody
    @Auth
    public ResultVo createOrder(@RequestBody @Valid OrderReq req) throws ParseException {
        logger.info("订单参数：{}", JSON.toJSONString(req));
        long start = System.currentTimeMillis();
        String orderId = orderService.submitOrder1(req);
        ResultVo resultVo = new ResultVo();

        if ((orderId == null) || (orderId == "")) {
            resultVo.put("msg", "订单创建失败");
        } else {
            resultVo.put("success", true);
            resultVo.put("data", orderId);
        }
        logger.info("下单耗费时间：{}", System.currentTimeMillis() - start);
        return resultVo;
    }

    /**
     * 取消订单
     *
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/cancel")
    @ResponseBody
    @Auth
    public ResultVo cancelOrder(Long orderId) {
        int result = orderService.cancelOrder(orderId, null);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", result);
        return resultVo;
    }

    @RequestMapping("/wxpay")
    @ResponseBody
    @Auth
    public Object getGzhPayConfig(String orderId, Long couponId, Integer points,Integer payMethod, HttpServletRequest request, HttpServletResponse response) {
        logger.info("orderId = {} , payMethod = {}",orderId , payMethod);
        Object resultVo = new Object();
        try {
            Order order;
            if (orderId.contains("X_OC_")) {
                order = orderService.getByPayNo(orderId);
            } else {
                order = orderMapper.selectByPrimaryKey(Long.parseLong(orderId));
            }

            if (order.getStatus() != 0) {
                return ResultVo.error("订单已经超时取消，请重新下单");
            }
            order.setPaytype(PayType.WX_PAY);//更新支付方式
            //获取一条可用支付通道
            PayChannel payChannel = payChannelService.getFirstChannel(order.getCentreId());
            double payAmount = payService.getPrePayAmount(order, points);
//           if (StringUtils.isNotBlank(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.YPL.getCode()) && payAmount > 0.01) {
                Centre centre = centreService.getCentreById(order.getCentreId());
                Member member = memberService.getByKey(order.getMid());
                //获取对应店铺
                Member teamMember = memberService.getByKey(order.gettMid());

                List<OrderProduct> orderProductList = orderProductMapper.getProductListByOrderId(order.getId());
                //修改订单支付id
                String sn = RandomStringUtils.randomAlphanumeric(10);
                String outTradeNo = "X_OC_".concat(sn);
                order.setOutTradeNo(outTradeNo);
                order.setPayMerchantNo(outTradeNo);
                orderService.update(order);

                JSONObject attach = new JSONObject();
                attach.put("type", WXPAY_ORDER);
                attach.put("orderId", order.getId());
                attach.put("chanelcode", PayChannelEnum.YPL.getCode());//通道编号
                attach.put("chanelname", PayChannelEnum.YPL.getValue());//通道名称
                //更新订单支付参数
                Map<String, Object> updMap = new HashMap<>();
                updMap.put("outTradeNo", order.getOutTradeNo());
                updMap.put("payAttach", JSON.toJSONString(attach));
                updMap.put("paystatus", PayStatus.PAYING.getCode());//更改支付状态为支付中
                updMap.put("paytype", 2);//公众号支付类型
                int updResult = orderService.updOrderPayAttach(updMap);
                if (updResult != 1) return ResultVo.error("支付参数异常");
                XLoginInfo xLoginInfo = new XLoginInfo();
                xLoginInfo.setMobile(member.getLoginMobile());
                xLoginInfo = xLoginInfoMapper.selectOne(xLoginInfo);
                member.setAppOpenid(xLoginInfo.getOpenId());

            resultVo = yfzPayutil.getPayConfig(order, payAmount, centre, orderProductList, member, JSON.toJSONString(attach), payMethod == null ? 1 : payMethod, true, yfzNotifyUrl, request, teamMember);
//            } else {
//                resultVo = getPayConfig(request, order, couponId, points, payAmount);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("<br/><br/>返回结果:" + resultVo.toString());
        return resultVo;
    }

    private ResultVo getPayConfig(HttpServletRequest request, Order order, Long couponId, Integer points, double payAmount) {
        String desc = "" + order.gettXiaoqu();
        JSONObject attach = new JSONObject();
        attach.put("type", WXPAY_ORDER + "");
        attach.put("orderId", order.getId());
        attach.put("couponId", couponId);
        attach.put("points", points);
        attach.put("chanelcode", PayChannelEnum.BASE_WX.getCode());//通道编号
        attach.put("chanelname", PayChannelEnum.BASE_WX.getValue());//通道名称
        String attachValue = attach.toJSONString();
        WxPayMpOrderResult result = null;
        boolean success = false;
        logger.info("getPayConfig配置：==================" + WXPAY_ORDER);
        while (!success) {
            try {
                logger.info("进入调起支付==================");
                result = myWxpayService.createJSPayRequest(order.getOpenid(), desc, order.getOutTradeNo()
                        , payAmount, notifyUrl, CusAccessObjectUtil.getIpAddress(request), attachValue);
                success = true;
                logger.info("getPayConfig配置回掉：==================" + notifyUrl);
            } catch (WxPayException e) {
                //201 商户订单号重，刷新订单号
                if ("INVALID_REQUEST".equalsIgnoreCase(e.getErrCode())) {
                    logger.info("订单号重复，刷新tradeNO重试：{}", order.getId());
                    order.setOutTradeNo(payService.refreshTradeNo(order.getId()));
                } else {
                    logger.info("到了错误==================" + e.getMessage());
                    return ResultVo.error(e.getMessage());
                }
            }
        }
        Order order1 = new Order();
        order1.setOutTradeNo(order.getOutTradeNo());
        order1.setOpenid(order.getOpenid());
        order1.setPaytype(order.getPaytype());
        orderService.updateOpenid(order1);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", result);
        resultVo.put("PayChannel", PayChannelEnum.BASE_WX.getCode());//支付通道
        return resultVo;
    }

    /**
     * 余额支付
     *
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/yupay")
    @ResponseBody
    @Auth
    public ResultVo balancePay(String orderId, Long couponId, Integer points, Long shipcardRecordId) {
        int result = 0;

        Order order = orderService.getByKey(Long.valueOf(orderId));
        //如果为大礼包订单
        if (order.getOrderType() == ProductType.FreeCharge.getType()) {
            productAuthorityService.MemberProductAuthoityUpdate(order);
        }

        if (shipcardRecordId == null) {
            //余额支付
            result = payService.balancePay(orderId, points);
        }

        ResultVo resultVo = new ResultVo();
        resultVo.put("success", (result > 0));
        return resultVo;
    }


    /**
     * 获取会员订单总数量
     */
    @RequestMapping("/count")
    @ResponseBody
    @Auth(arg = 0)
    public ResultVo getOrderCount(Long memberId) {
        List<Map<String, Object>> statusCounts = orderService.getStatusCounts(memberId);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", statusCounts);
        resultVo.put("canyinData", orderService.getCanyinOrderCounts(memberId));
        return resultVo;
    }



    /**
     * 提交订单
     *
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/activity/package/order/create")
    @ResponseBody
    @Auth
    public ResultVo createPackageOrder(@RequestBody @Valid OrderReq req) throws ParseException {
        logger.info("订单参数：{}", JSON.toJSONString(req));
        long start = System.currentTimeMillis();
        if(!req.getPlateType().equals(req.getScanCodePlateType())){
            if(req.getScanCodePlateType() == 0 && req.getPlateType() == 1){
                throw new BDException("请咨询粤轩公寓门店扫码取得优惠权限");
            }
        }
        String orderId = orderService.submitActivtyOrder(req);
        ResultVo resultVo = new ResultVo();

        if ((orderId == null) || (orderId == "")) {
            resultVo.put("msg", "订单创建失败");
        } else {
            resultVo.put("success", true);
            resultVo.put("data", orderId);
        }
//        redisTemplate.opsForValue().set("fromId" + orderId, req.getFromId(), 7, TimeUnit.DAYS);
        logger.info("下单耗费时间：{}", System.currentTimeMillis() - start);
        return resultVo;
    }





}
